package com.otitan.la.forest.industry.config;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.otitan.la.forest.industry.constant.StaticConstant;
import com.otitan.auth.framework.basepro.common.AuthCommon;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Description: java类作用描述
 * @Author: jiachangsen
 * @CreateDate: 2020/08/06 12:42
 * @UpdateUser: jiachangsen
 * @UpdateDate: 2020/08/06 12:42
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {


    private static final String CREATE_DATE = "createDate";
    private static final String CREATE_USER = "createUser";

    private static final String UPDATE_DATE = "updateDate";
    private static final String UPDATE_USER = "updateUser";

    private static final String IS_DELETE = "isDelete";
    private static final String SYS_MAIN = "sysmain";

    @Autowired
    private AuthCommon authCommon;


    @Override
    public void insertFill(MetaObject metaObject) {
        String userId = getLoginUserInfo();
        Date date = new Date();

        fillValue(metaObject, CREATE_DATE, date);
        fillValue(metaObject, CREATE_USER, userId);
        fillValue(metaObject, UPDATE_DATE, date);
        fillValue(metaObject, UPDATE_USER, userId);
        fillValue(metaObject, IS_DELETE, StaticConstant.NOT_DELETE);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Date date = new Date();
        String userId = getLoginUserInfo();
        fillValue(metaObject, UPDATE_DATE, date);
        fillValue(metaObject, UPDATE_USER, userId);
    }

    private String getLoginUserInfo() {
        JSONObject userEntity = null;
        try {
            userEntity = authCommon.getLoginUserInfo();
        } catch (UnavailableSecurityManagerException e) {
            log.error("【获取当前用户信息异常。。。】");
        }
        String userId = SYS_MAIN;
        if (userEntity != null) {
            userId = userEntity.get("id").toString();

        }
        return userId;
    }

    private void fillValue(MetaObject metaObject, String fieldName, Object value) {
        if (!metaObject.hasGetter(fieldName)) {
            return;
        }
        Object sidObj = metaObject.getValue(fieldName);
        if (sidObj == null && metaObject.hasSetter(fieldName) && value != null) {
            setFieldValByName(fieldName, value, metaObject);
        }
    }
}
